#+---------------------------------------------+
#| ProxyBot 0.7
#+---------------------------------------------+
#| Written by Alec Hussey
#| Copyright (C) 2008 MadSoft
#| Website: www.madsoft.org
#| License: GNU General Public License v3
#+---------------------------------------------+

class Config:
	def __init__(self, filename=".config"):
		self.filename = filename
	
	def __display_error(self):
		raise RuntimeError, "Failed to open configuration file."
	
	def get(self, key):
		try:
			cfgfile = open(self.filename, "r")
		except IOError:
			self.__display_error()
		
		el = cfgfile.read().splitlines()
		for line in el:
			kv = line.split(";")[0].split(":")
			if kv[0] == key:
				return kv[1]
		
		return None
	
	def set(self, key, value):
		try:
			cfgfile = open(self.filename, "w+")
			
			try:
				el = cfgfile.read().split(";")
				for line in el:
					kv = line.split(":")
					if kv[0] == key:
						cfgfile.write("%s:%s;\n" % (key, value))
					else:
						cfgfile.write("%s:%s;\n" % (kv[0], kv[1]))
			finally:
				cfgfile.close()
		except IOError:
			self.__display_error()	
	
	def insert(self, key, value):
		try:
			cfgfile = open(self.filename, "a")
			
			try:
				cfgfile.write("%s:%s;\n" % (key, value))
			finally:
				cfgfile.close()
		except IOError:
			self.__display_error()
	
	def delete(self, key):
		try:
			cfgfile = open(self.filename, "w+")
			
			try:
				el = cfgfile.read().split(";")
				for line in el:
					kv = line.split(":")
					if kv[0] != key:
						cfgfile.write("%s:%s;\n" % (kv[0], kv[1]))
					else:
						continue
			finally:
				cfgfile.close()
		except IOError:
			self.__display_error()
	
	def exists(self, key):
		if not self.get(key):
			return False
		else:
			return True
	
	def list_all(self):
		try:
			cfgfile = open(self.filename, "r")
		except IOError:
			self.__display_error()
		
		output = []
		el = cfgfile.read().splitlines()
		for line in el:
			kv = line.split(";")[0].split(":")
			output.append((kv[0], kv[1]))
		
		return output
